<script setup lang="ts">
import type { VbenFormProps } from '@vben/common-ui';

import type { VxeGridProps } from '#/adapter/vxe-table';

import { computed, ref } from 'vue';

import { useVbenModal } from '@vben/common-ui';
import { $t } from '@vben/locales';
import { getVxePopupContainer } from '@vben/utils';

import { Image, Popconfirm, Space } from 'ant-design-vue';

import { useVbenVxeGrid } from '#/adapter/vxe-table';
import {
  saleOrderPickUpExport,
  saleOrderPickUpList,
  saleOrderPickUpUpdate,
} from '#/api/hm/saleOrderPickUp';
import { commonDownloadExcel } from '#/utils/file/download';
import { columns, querySchema } from '#/views/hm/saleOrderPickUp/data';

import { useAccess } from '../../../../../../packages/effects/access/src/use-access';

const pickUpTypeParam = ref('');
const saleOrderIdParam = ref<number | string | undefined>('');
const saleProductIdParam = ref<number | string | undefined>('');
const productType = ref<number | string | undefined>('');
const title = computed(() => {
  return '提货回款历史';
});

const { hasAccessByRoles } = useAccess();
const isAdmin = computed(() => {
  return hasAccessByRoles(['admin', 'superadmin', 'ceo']);
});

const [BasicModal, modalApi] = useVbenModal({
  fullscreenButton: false,
  draggable: true,
  onCancel: handleCancel,
  onConfirm: handleCancel,
  onOpenChange: async (isOpen) => {
    if (!isOpen) {
      return null;
    }
    modalApi.modalLoading(true);
    const { productId, saleOrderId, pickUpType } = modalApi.getData() as {
      pickUpType?: string;
      productId?: number | string | undefined;
      saleOrderId?: number | string | undefined;
    };
    pickUpTypeParam.value = pickUpType === 'refundAmountHis' ? '0' : '1'; // 是否回款
    saleOrderIdParam.value = saleOrderId;
    saleProductIdParam.value =
      pickUpType === 'refundAmountHis' ? undefined : productId; // 是否回款
    productType.value =
      pickUpType === 'pickUpNumHis'
        ? 'CP'
        : (pickUpType === 'pickUpNumHisZP'
          ? 'ZP'
          : undefined);
    modalApi.modalLoading(false);
  },
});

const formOptions: VbenFormProps = {
  commonConfig: {
    labelWidth: 80,
    componentProps: {
      allowClear: true,
    },
  },
  schema: querySchema(),
  wrapperClass: 'grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4',
  // 处理区间选择器RangePicker时间格式 将一个字段映射为两个字段 搜索/导出会用到
  // 不需要直接删除
  fieldMappingTime: [
    ['pickUpTime', ['startTime', 'endTime'], ['YYYY-MM-DD', 'YYYY-MM-DD']],
  ],
};

const gridOptions: VxeGridProps = {
  checkboxConfig: {
    // 高亮
    highlight: true,
    // 翻页时保留选中状态
    reserve: true,
    // 点击行选中
    // trigger: 'row',
  },
  columns,
  height: 'auto',
  keepSource: true,
  pagerConfig: {},
  proxyConfig: {
    ajax: {
      query: async ({ page }, formValues = {}) => {
        return await saleOrderPickUpList({
          pageNum: page.currentPage,
          pageSize: page.pageSize,
          pickUpType: pickUpTypeParam.value,
          saleOrderId: saleOrderIdParam.value,
          saleProductId: saleProductIdParam.value,
          productType: productType.value,
          ...formValues,
        });
      },
    },
  },
  rowConfig: {
    keyField: 'pickUpId',
  },
  // 表格全局唯一表示 保存列配置需要用到
  id: 'hm-saleOrderPickUp-index',
};

const [BasicTable, tableApi] = useVbenVxeGrid({
  formOptions,
  gridOptions,
});

function handleDownloadExcel() {
  commonDownloadExcel(
    saleOrderPickUpExport,
    '销售订单提货、回款数据',
    tableApi.formApi.form.values,
    {
      fieldMappingTime: formOptions.fieldMappingTime,
    },
  );
}

async function handleCancel() {
  modalApi.close();
}
async function handleCancelRow(row: any) {
  row.status = 1;
  await saleOrderPickUpUpdate(row);
  tableApi.query();
}
</script>

<template>
  <BasicModal
    :close-on-click-modal="true"
    :title="title"
    class="h-[650px] w-[1100px]"
  >
    <BasicTable table-title="销售订单提货、回款列表" class="h-[500px]">
      <template #toolbar-tools>
        <Space>
          <a-button
            v-access:code="['hm:saleOrderPickUp:export']"
            @click="handleDownloadExcel"
          >
            {{ $t('pages.common.export') }}
          </a-button>
        </Space>
      </template>
      <template #url="{ row }">
        <Image :src="row.file" height="50px" />
      </template>
      <template #action="{ row }">
        <Popconfirm
          v-if="isAdmin && row.status === '0'"
          :get-popup-container="getVxePopupContainer"
          placement="left"
          title="确认作废该记录?"
          @confirm="handleCancelRow(row)"
        >
          <ghost-button danger @click.stop=""> 作废 </ghost-button>
        </Popconfirm>
      </template>
    </BasicTable>
  </BasicModal>
</template>
